import React, { PureComponent } from 'react'

export class App extends PureComponent {
  constructor() {
    super()

    // state中的数据不能直接修改，如果需要修改，应该需要修改全部数据
    this.state = {
      books: [
        { name: '你不知道的JS', price: 99, count: 1 },
        { name: 'JavaScript高级设计', price: 95, count: 2 },
        { name: 'React高级设计', price: 199, count: 3 },
        { name: 'Vue高级设计', price: 299, count: 4 },
      ],
      friend: {
        name: 'kobe',
      },
    }
  }

  addNewBook() {
    const newBook = {
      name: 'Angular高级设计',
      price: 88,
      count: 2,
    }

    const books = [...this.state.books]
    books.push(newBook)
    this.setState({ books })

    // 继承PureComponent，不会刷新页面，因为setState前后两次比较是相同的
    /* this.state.books.push(newBook)
    this.setState({ books: this.state.books }) */
  }

  increment(index) {
    const newBooks = [...this.state.books]
    newBooks[index].count += 1
    this.setState({
      books: newBooks,
    })
  }

  render() {
    const { books } = this.state

    return (
      <div>
        <h2>数据列表</h2>
        <ul>
          {books.map((item, index) => {
            return (
              <li key={index}>
                <span>
                  name: {item.name} - price: {item.price} - count: {item.count}
                </span>
                <button onClick={(e) => this.increment(index)}>+1</button>
              </li>
            )
          })}
        </ul>
        <button onClick={(e) => this.addNewBook()}>添加新数据</button>
      </div>
    )
  }
}

export default App
